
package branch.feature.qrcode_scan;

import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.mynewsapp.databinding.ActivityScanStyle1QrBinding;
import com.huawei.hms.hmsscankit.RemoteView;
import com.huawei.hms.ml.scan.HmsScan;

public class ScanStyle1Activity extends AppCompatActivity {
    private ActivityScanStyle1QrBinding binding;
    private @Nullable RemoteView remoteView;
    private HuaWeiRemoteViewManager remoteViewManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityScanStyle1QrBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initScanView(savedInstanceState);
    }

    private void initScanView(@Nullable Bundle savedInstanceState) {

        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        // get screen size
        float density = displayMetrics.density;
        int screenWidth = displayMetrics.widthPixels;
        int screenHeight = displayMetrics.heightPixels;
        float scanFrameSize = (300 * density);
        Rect rect = new Rect();
        rect.left = (int) (screenWidth / 2 - scanFrameSize / 2);
        rect.right = (int) (screenWidth / 2 + scanFrameSize / 2);
        rect.top = (int) (screenHeight / 2 - scanFrameSize / 2);
        rect.bottom = (int) (screenHeight / 2 + scanFrameSize / 2);

        RemoteView remoteView = new RemoteView.Builder()
                .setContext(this)
                .setBoundingBox(rect)
                .setFormat(HmsScan.QRCODE_SCAN_TYPE, HmsScan.DATAMATRIX_SCAN_TYPE)
                .build();
        if (remoteView != null) {
            remoteView.setOnResultCallback(result ->
            {
                if (result != null && result.length != 0 &&
                        result[0] != null && !TextUtils.isEmpty(result[0].getOriginalValue())
                ) {
                    onScanResultCallback(result[0].originalValue);
                }
            });
        }

        remoteViewManager = new HuaWeiRemoteViewManager(remoteView);

        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
        );
        binding.rim1.addView(remoteView, layoutParams);
    }

    private void onScanResultCallback(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
        finish();
    }


}
